package top.lingkang.authoritypro;

import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.transaction.annotation.Transactional;
import top.lingkang.authoritypro.data.dao.UserDao;
import top.lingkang.authoritypro.data.entity.*;

import javax.persistence.EntityManager;
import java.util.List;

@EntityScan(basePackages = {"top.lingkang.authoritypro.data.entity"})
@SpringBootApplication
public class AuthorityDemoApplication implements ApplicationRunner {

    public static void main(String[] args) {
        SpringApplication.run(AuthorityDemoApplication.class, args);
    }

    @Autowired
    private UserDao userDao;
    @Autowired
    private EntityManager entityManager;


    @Transactional// 涉及更新删除，需要开启事务
    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 获取会话,,,使用 unwrap 返回 EntityManager 的底层实现
        Session session = entityManager.unwrap(Session.class);

        User byUsername = userDao.findByUsername("123");
        if (byUsername == null) {
            User user = new User();
            user.setUsername("123");
            user.setPassword("123");
            user.setNickname("管理员");
            session.save(user);
            // springboot 2.3.12 使用的是 hibernate 5.4.x
            List username = session.createQuery("from User u where username=:username")
                    .setParameter("username", "123").list();
            System.out.println(username);

            Role role = new Role();
            role.setName("admin");
            session.save(role);

            UserToRole userToRole = new UserToRole();
            userToRole.setUser(user);
            userToRole.setRole(role);
            session.save(userToRole);

            Authority authority = new Authority();
            authority.setUrl("/**");
            session.save(authority);

            Menu menu = new Menu();
            menu.setCode("index");
            menu.setUrl("/index");
            menu.setSeq(0);
            menu.setTitle("主页");
            session.save(menu);

            session.save(new RoleToAuthority(role, authority));
            session.save(new RoleToMenu(role, menu));
        }
        // 此处要注意 使用User的细节
        List username = session.createQuery("from User u where username=:username")
                .setParameter("username", "123").list();
        System.out.println(username);
    }
}
